package db

import (
	log "github.com/sirupsen/logrus"
	"src/db/db_modle"
	"src/error_msg"
)

// 获取用户银行信息
func GetBankInfoById(uid uint) []db_modle.BankDetails {
	orm := GetMysqlOrm()
	defer orm.Close()
	bankDetail := make([]db_modle.BankDetails, 0)
	result := orm.Where("user_id = ?", uid).Find(&bankDetail)
	if e := result.Error; e != nil {
		log.Error(e.Error())
		return []db_modle.BankDetails{}
	}
	return bankDetail
}

// 注册同一银行卡不同身份证数量
func GetNumOfIdBandToOneBankAccount(uid uint, logId string) (int64, error) {
	bd := GetBankInfoById(uid)
	if len(bd) == 0 {
		ne := error_msg.InformationNotFoundError
		log.Error(ne, logId)
		return 0, ne
	}
	orm := GetMysqlOrm()
	defer orm.Close()
	var max int64
	bankDetail := make([]db_modle.BankDetails, 0)
	for _, v := range bd {
		//每个银行卡，注册的身份证数量
		result := orm.Where("user_id = ?", uid).Where("bank_account = ?", v.BankAccount).Group("card").Find(&bankDetail)
		if e := result.Error; e != nil {
			log.Error(e.Error(), logId)
			return 0, e
		}
		if result.RowsAffected > max {
			max = result.RowsAffected
		}
		//log.Debugf("注册同一银行卡不同身份证数量 %+v \n", bankDetail)
	}
	return max, nil
}

// 注册同一银行卡不同手机号数量
func GetNumOfPhoneNumBandToOneBankAccount(uid uint, logId string) (int64, error) {
	bd := GetBankInfoById(uid)
	if len(bd) == 0 {
		ne := error_msg.InformationNotFoundError
		log.Error(ne, logId)
		return 0, ne
	}
	orm := GetMysqlOrm()
	defer orm.Close()
	var max int64
	bankDetail := make([]db_modle.BankDetails, 0)
	for _, v := range bd {
		//每个银行卡，注册的手机号数量
		result := orm.Where("user_id = ?", uid).Where("bank_account = ?", v.BankAccount).Group("cell_phone").Find(&bankDetail)
		if e := result.Error; e != nil {
			log.Error(e.Error(), logId)
			return 0, e
		}
		if result.RowsAffected > max {
			max = result.RowsAffected
		}
		//log.Debugf("注册同一银行卡不同手机号数量 %+v \n", bankDetail)
	}
	return max, nil
}

// 同一身份证号被注册的uid数不超过两个
func GetNumOfUidOnOneIdCard(uid uint, logId string) (int64, error) {
	bd := GetBankInfoById(uid)
	if len(bd) == 0 {
		ne := error_msg.InformationNotFoundError
		log.Error(ne, logId)
		return 0, ne
	}
	orm := GetMysqlOrm()
	defer orm.Close()
	var max int64
	bankDetail := make([]db_modle.BankDetails, 0)
	for _, v := range bd {
		// 每个身份证的uid是否都是这个人
		result := orm.Where("card = ?", v.Card).Group("user_id").Find(&bankDetail)
		if e := result.Error; e != nil {
			log.Error(e.Error(), logId)
			return 0, e
		}
		if result.RowsAffected > max {
			max = result.RowsAffected
		}
		//log.Debugf("同一身份证号被注册的uid数不超过两个 %+v \n", bankDetail)
	}
	return max, nil
}
